package ui.window;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import control.GameControl;
import dao.DataBase;
import ui.Img;
import util.JDialogUtil;

@SuppressWarnings("serial")
public class JDialogConfig extends JDialog {

	private JButton btnOk = new JButton("确定");

	private JButton btnCancel = new JButton("取消");
	
	private JButton btnUser = new JButton("应用");

	private JTextCtrl[] keyText = new JTextCtrl[8];
	
	private GameControl gameControl;
	
	private JLabel errorMsg = new JLabel();
	
	private JList<String> skinList = null;
	
	private JPanel skinView = null;
	
	private DefaultListModel<String> skinData = new DefaultListModel<String>();
	
	private final static Image IMG_PSP = new ImageIcon("data/psp.png").getImage(); 
	
	private Image[] skinViewList = null;
	
	private JDialogEnter dialogEnter;
	
	private final static String[] METHOD_NAMES = {
		"keyRight","keyUp","keyLeft","keyDown",
		"keyFunLeft","keyFunUp","keyFunRight","keyFunDown"
	};
	
	private final static String PATH = "data/control.dat";

	public JDialogConfig(JPanelGame panelGame, GameControl gameControl){
		//设置dialog到主窗体
		this.add(panelGame);
		//获得游戏控制器对象 
		this.gameControl = gameControl;
		//设置布局管理器为边界布局
		this.setLayout(new BorderLayout());
		//设置标题
		this.setTitle("设置");
		//初始化按键输入框
		this.initKeyText();
		//添加主面板
		this.add(createMainPanel(), BorderLayout.CENTER);
		//添加按钮面板
		this.add(createButtonPanel(), BorderLayout.SOUTH);
		//设置不能变大小
		this.setResizable(false);
		//设置大小
		this.setSize(640, 350);
		//居中
		JDialogUtil.setDialogCenter(this);
		//设置模态
		this.setModal(true);
	}
	
	/**
	 * 初始化设置对话框
	 */
	public void showJDialogCfg() {
		this.initWordInKeyText();
		this.errorMsg.setText(null);
		this.setVisible(true);
	}
	
	/**
	 * 显示验证对话框
	 */
	private void showDialogEnter() {
		if(skinList.getSelectedIndex() == 2) {
			this.skinView.setVisible(false);
			dialogEnter = new JDialogEnter();
			dialogEnter.showJDialogEnter();
			if(!dialogEnter.isPass()) {
				this.getSkinList().setVisible(false);
				this.btnOk.setEnabled(false);
				this.btnUser.setEnabled(false);
				this.skinView.setVisible(false);
				this.errorMsg.setText("没密码你也敢乱试,信不信我分分钟让你关机,还不速速取消！");
			}else if (dialogEnter.isPass()) {
				this.skinView.setVisible(true);
			}
		}
	}

	/**
	 * 初始化按键输入框
	 */
	public void initKeyText() {
		int x = 6;
		int y = 54;
		int w = 64;
		int h = 20;
		for (int i = 0; i < 4; i++) {
			this.keyText[i] = new JTextCtrl(x, y, w, h, METHOD_NAMES[i]);
			this.keyText[i].setHorizontalAlignment(JTextField.CENTER);
			y += 28;
		}
		x = 560;
		y = 56;
		for (int i = 4; i < 8; i++) {
			this.keyText[i] = new JTextCtrl(x, y, w, h, METHOD_NAMES[i]);
			this.keyText[i].setHorizontalAlignment(JTextField.CENTER);
			y += 28;
		}
	}

	/**
	 * 初始化输入框内文字
	 */
	private void initWordInKeyText() {
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PATH));
			@SuppressWarnings("unchecked")
			HashMap<Integer, String> cfgSet = (HashMap<Integer, String>)ois.readObject();
			ois.close();
			Set<Entry<Integer, String>> entryset = cfgSet.entrySet();
			for (Entry<Integer, String> e : entryset) {
				for(JTextCtrl tc : keyText){
					if(tc.getMethodName().equals(e.getValue())) {
						tc.setKeyCode(e.getKey());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建按钮面板
	 */
	private JPanel createButtonPanel() {
		//创建按钮面板，流式布局
		JPanel jp = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		//给确定按钮增加事件监听
		this.btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(writeConfig()) {
					setVisible(false);
					gameControl.setOver();
				}
			}
		});
		this.errorMsg.setForeground(Color.RED);
		jp.add(errorMsg);
		jp.add(btnOk);
		//给取消按钮增加事件监听
		this.btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
				gameControl.setOver();
				getSkinList().setVisible(true);
				btnOk.setEnabled(true);
				btnUser.setEnabled(true);
				skinView.setVisible(true);
				skinList.setSelectedIndex(0);
//				errorMsg.setText("此乃小瑶同学专属皮肤，尔等还不速速取消！");
			}
		});
		jp.add(btnCancel);
		//给应用按钮增加事件监听
		this.btnUser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				writeConfig();
				gameControl.repaint();
			}
		});
		jp.add(btnUser);
		return jp;
	}

	/**
	 * 创建主面板（选项卡面板）
	 */
	private JTabbedPane createMainPanel() {
		JTabbedPane jtp = new JTabbedPane();
		jtp.addTab("控制设置", this.createControlPanel());
		jtp.addTab("皮肤设置", this.createSkinPanel());
		return jtp;
	}
	
	/**
	 * 玩家皮肤面板
	 */
	private JPanel createSkinPanel() {
		JPanel panel = new JPanel(new BorderLayout());
		File dir = new File(Img.GRAPHICS_PATH);
		File[] files = dir.listFiles();
		this.skinViewList = new Image[files.length];
		for (int i = 0; i < files.length; i++) {
			//增加选项
			this.skinData.addElement(files[2-i].getName());
			//增加预览图
			this.skinViewList[i] = new ImageIcon(files[2-i].getPath() + "\\view.jpg").getImage();
		}
		//TODO 从数据库取出view图
		this.skinViewList[2] = new ImageIcon(DataBase.getBytes()).getImage();
		//添加列表数据到列表
		this.skinList = new JList<String>(this.skinData);
		//设置默认选中第一个
		this.skinList.setSelectedIndex(0);
		this.skinList.addMouseListener(new MouseAdapter() {
			public void mouseReleased(MouseEvent e) {
				showDialogEnter();
				repaint();
			}
		});
		this.skinView = new JPanel(){
			@Override
			public void paintComponent(Graphics g){
				Image showImage = skinViewList[skinList.getSelectedIndex()];
				int x = this.getWidth() - showImage.getWidth(null) >> 1;
				int y = this.getHeight() - showImage.getHeight(null) >> 1;
				g.drawImage(showImage, x, y, null);
			}
		};
		panel.add(new JScrollPane(this.skinList), BorderLayout.WEST);
		panel.add(this.skinView, BorderLayout.CENTER);
		return panel;
	}

	/**
	 * 玩家控制设置面板
	 */
	private JPanel createControlPanel() {
		JPanel jp = new JPanel(){
			@Override
			public void paintComponent(Graphics g){
				g.drawImage(IMG_PSP, 0, 0, null);
			}
		};
		//设置布局管理器
		jp.setLayout(null);
		for (int i = 0; i < keyText.length; i++) {
			jp.add(keyText[i]);
		}
		return jp;
	}

	/**
	 * 写入游戏配置
	 * @return 
	 */
	private boolean writeConfig() {
		HashMap<Integer, String> keySet = new HashMap<Integer, String>();
		for (int i = 0; i < this.keyText.length; i++) {
			int keyCode = this.keyText[i].getKeyCode();
			if(keyCode == 0) {
				this.errorMsg.setText("错误按键！");
				return false;
			}
			keySet.put(keyCode, this.keyText[i].getMethodName());
		}
		if(keySet.size() != 8) {
			this.errorMsg.setText("重复按键！");
			return false;
		}
		try {
			//切换皮肤
			Img.setSkin(this.skinData.get(this.skinList.getSelectedIndex()));
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(PATH));
			oos.writeObject(keySet);
			oos.close();
		} catch (Exception e) {
			this.errorMsg.setText(e.getMessage());
			return false;
		}
		this.errorMsg.setText(null);
		return true;
	}

	public JList<String> getSkinList() {
		return skinList;
	}
}
